package edu.biwu.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.sql.SQLException;

@Component
public class TransactionManager {

    @Autowired //只有创建connectionFactory实例才能在里面使用@Autowired
    private ConnectionFactory connectionFactory;

    @Autowired
    private ThreadLocal<Connection> threadLocal;

    public void beginTransaction(){
        Connection connection = connectionFactory.currentThreadConnection();

        try {
            connection.setAutoCommit(false); //设置手动提交 开启事务
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
        }
    }

    public void commitTansaction(){
        Connection connection = connectionFactory.currentThreadConnection();
        try {
            connection.commit();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public void rollbackTransaction(){
        Connection connection = connectionFactory.currentThreadConnection();
        try {
            connection.rollback();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public void releaseConnection(){
        Connection connection = connectionFactory.currentThreadConnection();
        try {
            connection.close();
            threadLocal.remove(); //将数据库连接与当前线程解绑,解绑后连接可以与其他绑定的线程绑定 可能出现 A线程 与 B线程 绑定同一个连接
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
